<!--
 * @Descripttion: 
 * @version: 
 * @Author: mmzhang
 * @Date: 2021-07-21 10:45:02
 * @LastEditTime: 2023-02-14 21:02:47
-->
<template>
  <div class="subscription-list">
    <div v-show="showStatus">
      <date-search ref="dateSearch" @onResolve="resolveFun"></date-search>
      <!--查询-->
      <dt-search ref="search" :labelWidth="80" :xl="4" @reset="resetFun" @change="onValueChange">
      </dt-search>
      <!--统计信息-->
      <order-count ref="orderCount" @onChange="changeCountType"></order-count>
      <!--足未签-->
      <p class="tip-text" v-if="showCumulateNotFlag && noContractContent != null">
        <Icon type="md-alert" :size="18" color="#FAAD14"
          style="line-height:26px;margin-right:10px;" />
        {{noContractContent}}
      </p>
      <!--净值数据-->
      
      <p class="tip-text" v-if="showNetWorthFlag && countType==0 && adjustCount!=0">
        <Icon type="md-alert" :size="18" color="#FAAD14"
          style="line-height:26px;margin-right:10px;" />
        您所选择的统计周期内存在订单调整，如订单金额或面积与统计数据不同，请查看净值数据
        <span class="view hand" @click="viewFun">立即查看</span>
      </p>
      <!--净值文案-->
      <p class="tip-text" v-if="countType!=0">
        <Icon type="md-alert" :size="18" color="#FAAD14"
          style="line-height:26px;margin-right:10px;" />
        查看净值数据时，仅可切换顶部日期，不可进行二次筛选
      </p>
    </div>
    <dt-grid ref="table" :page="page" :onFetch='onFetch'>
      <div class="flex btn-content" slot="btn">
        <Button type="default" @click="changeShow()"
          style="margin-right:8px;">{{showStatusTxt}}</Button>
        <Button type="primary" @click="adjustOrder()" v-if="unlocking('0104010400')"
          style="margin-right:8px;">认购单调整</Button>
        <Button type="primary" @click="exportFun(0)" v-if="unlocking('0104010102')"
          style="margin-right:8px;">导出</Button>
        <Button type="primary" @click="exportFun(1)"
          v-if="unlocking('0104010103')">全号导出</Button>
        <Button type="primary" style="margin-left:8px;"> <a
            href="https://images.tospurfang.com/doc/%E8%AE%A4%E8%B4%AD%E5%8D%95%E6%93%8D%E4%BD%9C%E8%AF%B4%E6%98%8E.pdf"
            style="color:#fff;" target="_blank">查看操作指引</a>
        </Button>
        <Button type="primary" class="operation" style="margin-left: 8px"
          v-if="unlocking('0104010104')" @click="operationClick">查看导出记录</Button>
      </div>
    </dt-grid>

    <dt-loading :loading="loading"></dt-loading>
    <!--客户详情-->
    <Modal v-model="detailsFlag" title="客户详情" width="80%" :styles="{top:'5%'}"
      :footer-hide="true">
      <detail-page v-if="detailsFlag" :detailsParams="detailsParams"></detail-page>
    </Modal>
    <operation-record ref="operationRecord"></operation-record>
  </div>
</template>

<script>
  import SubColumn from './subscriptionColumn'
  import detailPage from '../../../allCustomersManagement/details.vue'
  import searchOpt from './search'
  import subMgr from '@/biz/sales/subOrder'
  import subCommonMgr from '@/biz/sales/salesCommon'
  import dt from '@dt/dt'
  import dateSearch from '@/components/dateSearch.vue'
  import ParamsDate from './subDate.js'
  import ParamsCount from './orderCount'
  import orderCount from '../../components/orderCount.vue'
  let searchNum = 0
  export default {
    props: {
      value: Object
    },
    data() {
      return {
        loading: false,
        detailsFlag: false,
        detailsParams: {},
        isFileList: false,
        searchInfo: {
          statusList: [], //状态
          productIds: [], //产品
          buildingIds: [],
          unitIds: [],
        },
        filterParams: {},
        page: {
          rows: 50,
          current: 1
        },
        countList: [],
        countVal: {},
        checkIndex: 5,
        resolveTime: {
          startTime: '',
          endTime: ''
        },
        containDate: [],
        showStatus: true,
        showStatusTxt: '收起筛选',
        showCumulateNotFlag: false,
        noContractContent: '',
        tips: '',
        countType: 0, // 0表示总销
        showNetWorthFlag: false,
        adjustCount:0
      }
    },
    components: {
      detailPage,
      dateSearch,
      orderCount
    },
    created() {
      this.countList = new ParamsCount(this).options().countList
      this.countVal = new ParamsCount(this).options().countVal
      this.tips = new ParamsCount(this).options().tips
    },
    mounted() {
      let _this = this
      let containDate = []

      this.showCumulateNotFlag = this.$route.params.showCumulateNotFlag

      // 净值
      this.showNetWorthFlag = this.$route.params.showNetWorthFlag

      let retainParams = dt.memory.get('subOrder_params')

      this.$refs.table.init(this, new SubColumn(this), {
        orderCode: this.$route.params.orderCode
      })
      this.$refs.search.init(this.$refs.table, new searchOpt(this), this
        .searchInfo)

      if (this.value.search) {
        Object.keys(this.searchInfo).map(function(key) {
          _this.value.search[key] && (_this.searchInfo[key] = _this.value.search[key]) //比较key
        })
      }

      // if (this.value.search) {
      //   this.$refs.search.update(new searchOpt(this), this.value.search)
      // }
      
      // 初始化
      this.$refs.dateSearch.initOptions(new ParamsDate(this).options())

      this.$nextTick(function() {
        this.$refs.table.throwFilter()?.import(this.value.filter)
        if (retainParams) {
          // 处理展示统计数据
          this.countType = retainParams.countType || 0
          this.resolveCountType()
          this.$refs.orderCount.changeType(this.countType)
          if(this.countType!=0){
            this.$refs.search.init(this.$refs.table, new searchOpt(this).options(), this
            .searchInfo)
          }

          containDate = retainParams.containDate

          this.$refs.dateSearch.setDateFun(retainParams.checkIndex, retainParams.checkTime,
            containDate)
          let resolveLinkTime = {
            startTime: retainParams.checkTime[0] ? retainParams.checkTime[0] : '',
            endTime: retainParams.checkTime[1] ? retainParams.checkTime[1] : ''
          }

          Object.keys(this.searchInfo).map(function(key) {
            retainParams[key] && (_this.searchInfo[key] = retainParams[key]) //比较key
          })
          retainParams.rows && (this.page.rows = retainParams.rows)
          retainParams.page && (this.page.current = retainParams.page)
          retainParams.filter && _this.$refs.table.throwFilter().import(retainParams
            .filter)
          this.resolveFun(retainParams.checkIndex, resolveLinkTime, containDate)
        } else {
          this.$refs.dateSearch.initDateFun()
          
        }
      })

    },
    methods: {
      viewFun() {
        this.countType = 1
        this.$refs.orderCount.changeType(1)
        this.changeCountType(1)
      },
      resolveCountType(){
        if (this.countType == 0) {
          this.countList = new ParamsCount(this).options().countList
          this.countVal = new ParamsCount(this).options().countVal
          this.tips = new ParamsCount(this).options().tips
        } else {
          if (this.countType == 1) {
            this.countList = new ParamsCount(this).options().countMoneyList
            this.tips = new ParamsCount(this).options().tipsMoney
          } else {
            this.countList = new ParamsCount(this).options().countAreaList
            this.tips = new ParamsCount(this).options().tipsArea
          }
          this.countVal = new ParamsCount(this).options().countActualVal
        }
      },
      changeCountType(countType) {
        this.showNetWorthFlag = false
        this.countType = countType

        // 处理展示统计数据
        this.resolveCountType()

        this.searchInfo = {
          housesId: dt.buildInfo().housesId,
          statusList: [], //状态
          productIds: [], //产品
          buildingIds: [],
          unitIds: [],
          isWeb: true
        }
        this.$refs.table.clearFilter()
        this.$refs.search.init(this.$refs.table, new searchOpt(this).options(), this
          .searchInfo)

        this.loading = true
        this.$refs.table.update(new SubColumn(this))

        // 保留订单状态参数
        this.searchInfo.statusList = this.filterParams.statusList

        this.$refs.table.fetch()
      },
      changeShow() {
        this.showStatus = !this.showStatus
        this.showStatusTxt = this.showStatus ? '收起筛选' : '展开筛选'
        this.$refs.table.fixHeight()
      },
      resetFun() {
        this.$refs.search.init(this.$refs.table, new searchOpt(this).options(), this
          .searchInfo)
      },
      operationClick() {
        this.$refs.operationRecord.show('export_subscriptionOrder', 'M_12', this.$dt
          .buildInfo().housesId)
      },
      resolveFun(checkIndex, resolveTime, containDate) {
        this.checkIndex = checkIndex
        this.resolveTime = resolveTime
        this.containDate = containDate
        this.loading = true
        this.$refs.table.update(new SubColumn(this))
        this.$refs.table.fetch()
      },
      adjustOrder() {
        this.$router.push({
          name: `subScriptionAdjust`,
        })
      },
      showTips() {
        this.$refs.tipsPage.show()
      },
      onValueChange() {
        this.$emit('input', { search: this.$refs.table.searchInfo, filter: this.$refs.table.throwFilter().export()})
      },
      onFetch(data) {
        // 足未签,净值提示信息
        if (searchNum >= 1) {
          this.showCumulateNotFlag = false
          this.showNetWorthFlag = false
        }
        searchNum += 1
        data.housesId = dt.buildInfo().housesId
        data.isWeb = true
        
        this.onValueChange()
        
        if (this.checkIndex == null && this.$tool.dateDiff(this.resolveTime.startTime, this
            .resolveTime.endTime).Y >= 2) {
          this.$Message.info('自定义日期跨度至多两年')
          return new Promise((resolve, reject) => {
            resolve()
          }).then(res => {
            this.noContractContent = ''
            if (this.countType) {
              this.countVal = new ParamsCount(this).options().countActualVal
            } else {
              this.countVal = new ParamsCount(this).options().countVal
            }
            this.loading = false
            this.$refs.orderCount.initData(this.tips, this.countList, this.countVal)
            return {
              list: [],
              total: 0
            }
          })
        } else {
          // 处理日期
          data.startDate = this.resolveTime.startTime ? this.resolveTime.startTime : ''
          data.endDate = this.resolveTime.endTime ? this.resolveTime.endTime : ''
          data.orderDateType = this.containDate

          this.filterParams = {
            ...data
          }

          this.getOrderStatistics()

          return subMgr.getSubOrderList(data).then(res => {
            this.$refs.table.fixHeight()
            return res
          }).catch(err => {})
        }
      },
      getOrderStatistics() {
        //订单净值数据
        if (this.countType || this.showNetWorthFlag) {
          let params = {
            orgId: dt.buildInfo().housesId,
            buildingId: dt.buildInfo().housesId,
            level: 4,
            orderDateType: this.filterParams.orderDateType,
            buildingName: '',
            coopModes: [],
            endTime: this.filterParams.endDate,
            productTypes: [],
            companyIds: [],
            startTime: this.filterParams.startDate,
            developerAbbreviations: []
          }

          subCommonMgr.getOrdernNetWorth(params).then(res => {
            this.loading = false
            if (this.showNetWorthFlag) {
              this.adjustCount = res.subscribeAdjustmentAmount + res
                .subscribeAdjustmentArea + res.contractAdjustmentAmount + res
                .contractAdjustmentArea
            } else {
              this.adjustCount = 0
              this.countVal = { ...res }
              this.$refs.orderCount.initData(this.tips, this.countList, this.countVal)
            }
          }).catch(err => {
            this.loading = false
            this.showNetWorthFlag = false
            this.adjustCount = 0
            this.countVal = new ParamsCount(this).options().countActualVal
            this.$refs.orderCount.initData(this.tips, this.countList, this.countVal)
          })
        }

        // 订单统计数据
        if (this.countType == 0) {
          let params = { ...this.filterParams }
          params.orderType = 'SUBSCRIPTION'

          subCommonMgr.getOrderStatistics(params).then(res => {
            this.loading = false
            this.noContractContent = res.noContractContent
            this.countVal = { ...res }
            this.$refs.orderCount.initData(this.tips, this.countList, this.countVal)
          }).catch(err => {
            this.loading = false
            this.noContractContent = ''
            this.countVal = new ParamsCount(this).options().countVal
            this.$refs.orderCount.initData(this.tips, this.countList, this.countVal)
          })
        }
      },
      // 保留列表查询参数
      retainParamsFun() {
        let params = Object.assign({
          showTab: 'subList',
          checkIndex: this.checkIndex,
          containDate: this.containDate,
          checkTime: [this.resolveTime.startTime, this.resolveTime.endTime],
          filter: this.$refs.table.throwFilter().export(),
          countType:this.countType
        }, this.filterParams)
        dt.memory.set('subOrder_params', params)
      },
      // 客户姓名链接到客户资料
      onLinkUser(row) {
        if (row.customerName == '-') {
          return false
        }
        this.detailsFlag = true
        this.detailsParams = {
          customerId: row.customerId,
          userCustomerId: row.userCustomerId,
          buildingId: dt.buildInfo().housesId,
          userId: dt.userInfo().userId,
          cityCode: dt.buildInfo().cityId,
        }
      },
      // 查看
      detailFun(row) {
        let orderParams = {
          orderNum: row.orderCode, // 单号
          businessId: row.orderId, // 业务id
          buildingId: this.$dt.buildInfo().housesId,
          subscriptionId: ''
        }

        this.linkOrderFun(orderParams)
      },
      // 导出
      exportFun(exportType) {
        let params = { ...this.filterParams }
        params.exportType = exportType
        subMgr
          .exportOrder(params)
          .then((res) => {})
          .catch((err) => {})
      },
      // 重置
      resetNumFun(){
        searchNum = 0
      }
    },
  }
</script>
<style lang="scss" scoped>
  .subscription-list {
    .sub-total {
      line-height: 32px;
      color: #D9001B;
    }
  }

  .tip-text {
    width: 100%;
    margin: 10px 0;
    line-height: 40px;
    color: #a30014;
    background-color: rgba(254, 252, 236, 1);
  }

  .view {
    margin-left: 20px;
    color: #2d8cf0;
  }
</style>